package web

import (
	"commerce/cache"
	"commerce/common"
	"commerce/data"
	"commerce/req"
	"commerce/utils"
	"commerce/vo"
	"encoding/json"
	"fmt"
	"net/http"
	"strconv"
	"strings"
	"time"
)

/* 此文件是 app 用户业务 请求 */

func SendEmailHandler(w http.ResponseWriter, r *http.Request) {

	member := extractUserFromContext(r)
	if member == nil || member.Mid <= 0 {
		common.DisplayTokenErr(w, http.StatusUnauthorized)
		return
	}
	var emailCodeReq req.EmailCodeReq
	err := json.NewDecoder(r.Body).Decode(&emailCodeReq)
	if err != nil {
		common.Error.Printf("SendEmailHandler err:%v", err)
		j, _ := json.Marshal(vo.Err(err.Error()))
		w.Header().Set("Content-Type", "application/json")
		w.WriteHeader(http.StatusOK)
		w.Write(j)
		return
	}
	code, _ := cache.Get(common.SEND_EMAIL_CODE_PREFIX + emailCodeReq.Email)
	now := time.Now().Unix()
	var emailCode string
	if len(code) > 0 {
		split := strings.Split(code, "_")
		emailCode = split[0]
		secTimes, _ := strconv.ParseInt(split[1], 10, 64)
		// 2分钟内才能发一次
		if now-secTimes < 120 {
			common.Error.Printf("2.SendEmailHandler err:%v", err)
			j, _ := json.Marshal(vo.Err("请稍候重试"))
			w.Header().Set("Content-Type", "application/json")
			w.WriteHeader(http.StatusOK)
			w.Write(j)
			return
		}
	} else {
		emailCode = utils.GenerateCode(6)
		code = fmt.Sprintf("%s_%d", emailCode, now)
		cache.SetWithTTL(common.SEND_EMAIL_CODE_PREFIX+emailCodeReq.Email, code, 10*60)
	}

	err = utils.Send(emailCodeReq.Email, "绑定邮箱验证码", emailCode)
	if err != nil {
		common.Error.Printf("SendEmailHandler err:%v", err)
		j, _ := json.Marshal(vo.Err(err.Error()))
		w.Header().Set("Content-Type", "application/json")
		w.WriteHeader(http.StatusOK)
		w.Write(j)
		return
	}
	j, _ := json.Marshal(vo.Ok(nil))
	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(http.StatusOK)
	w.Write(j)
}

func BindEmailHandler(w http.ResponseWriter, r *http.Request) {

	member := extractUserFromContext(r)
	if member == nil || member.Mid <= 0 {
		common.DisplayTokenErr(w, http.StatusUnauthorized)
		return
	}
	var emailReq req.BindEmailReq
	err := json.NewDecoder(r.Body).Decode(&emailReq)
	if err != nil {
		common.Error.Printf("BindEmailHandler err:%v", err)
		j, _ := json.Marshal(vo.Err(err.Error()))
		w.Header().Set("Content-Type", "application/json")
		w.WriteHeader(http.StatusOK)
		w.Write(j)
		return
	}
	tokenKey := common.SEND_EMAIL_CODE_PREFIX + emailReq.Email
	code, _ := cache.Get(tokenKey)
	if len(code) == 0 || emailReq.EmailCode != strings.Split(code, "_")[0] {
		common.Error.Println("2.BindEmailHandler 验证码错误")
		j, _ := json.Marshal(vo.Err("验证码错误"))
		w.Header().Set("Content-Type", "application/json")
		w.WriteHeader(http.StatusOK)
		w.Write(j)
		return
	}
	cache.Delete(tokenKey)

	err = data.UpdateMemberEmail(member.Mid, emailReq.Email)

	if err != nil {
		common.Error.Printf("3.BindEmailHandler :%v", err)
		j, _ := json.Marshal(vo.Err("系统异常，请稍候重试"))
		w.Header().Set("Content-Type", "application/json")
		w.WriteHeader(http.StatusOK)
		w.Write(j)
		return
	}
	j, _ := json.Marshal(vo.Ok(nil))
	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(http.StatusOK)
	w.Write(j)
}
